package com.neu.canteen.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.neu.canteen.domain.FoodType;
import com.neu.canteen.service.FoodTypeService;
import com.neu.canteen.service.impl.FoodTypeServiceImpl;
import com.neu.canteen.utils.JsonModel;
import com.neu.canteen.utils.JsonUtil;

public class FoodTypeController extends HttpServlet{
	
 
	
	private FoodTypeService foodTypeService;
	 
	public FoodTypeController(){
		foodTypeService = new FoodTypeServiceImpl();
	}
		
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	
		
		List<FoodType> foodTypes = foodTypeService.findAll();
		
		JsonModel<List<FoodType>> jsonModel = new JsonModel<>();
		jsonModel.setRows(foodTypes);
		jsonModel.setTotal(foodTypes.size());
		
		resp.getWriter().print(JsonUtil.toJSONString(jsonModel));
	}
	
	
	//get 获取
	//post 添加、删除、编辑
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	
		//思路
		    //获取参数
		        //   |-- req.getParameter("xxxx")
		    //service
		        //dao 
		             //insert
		    //响应给浏览器
		        //{"success":true|false,"msg":"xx"}
		
		//add
		//delete
		
		
		
		String icon = req.getParameter("icon");
		String name = req.getParameter("name");
		String action = req.getParameter("action"); //添加add 删除delete
		JsonModel jsonModel = new JsonModel();
		
		int result=-1;
		if("add".equals(action)){

			FoodType foodType = new FoodType();
			foodType.setIcon(icon);
			foodType.setName(name);
			
			result = foodTypeService.add(foodType);
		}
		else if("del".equals(action)){
			
			String id = req.getParameter("id");
			int d=Integer.parseInt(id);
			FoodType foodType=new FoodType();
			foodType.setIcon(id);
			result=foodTypeService.deleteFoodTypeId(d);
		}
		else if ("update".equals(action)) {
			FoodType foodType = new FoodType();
			String id = req.getParameter("id");
			int d=Integer.parseInt(id);
			
			
			foodType.setId(d);
			
			
			foodType.setIcon(icon);
			foodType.setName(name);
			result=foodTypeService.updataFoodtype(foodType);
		}
		
		
		if(result==-1){
			jsonModel.setMsg("失败");
			jsonModel.setSuccess(false);
		}else{
			jsonModel.setMsg("成功");
			jsonModel.setSuccess(true);
		}
		resp.getWriter().print(JsonUtil.toJSONString(jsonModel));//{"success":true,"msg":"xx",..}
	}
	
}
